package org.bpms.service.admin;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.bpms.model.admin.Member;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiResult;

/**
 * 微信关注用户操作接口
 * @author hupei
 *
 */
public class MemberService {
    /** 
     * 将emoji表情替换成* 
     *  
     * @param source 
     * @return 过滤后的字符串 
     */	
    public static String filterEmoji(String source) {  
        if(StringUtils.isNotBlank(source)){  
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*");  
        }else{  
            return source;  
        }  
    }	
	/**
	 * 保存关注用户信息
	 * @param member
	 */
	@Before(Tx.class)
	public void saveOrUpdate(ApiResult apiResult){
		
		Member member = new Member();
		member.set("id", apiResult.getStr("openid"));
		member.set("sex", apiResult.getInt("sex"));
		member.set("nickname", filterEmoji(apiResult.getStr("nickname")));
		member.set("city", apiResult.getStr("city"));
		member.set("province", apiResult.getStr("province"));
		member.set("country", apiResult.getStr("country"));
		if (null !=apiResult.getStr("headimgurl") && apiResult.getStr("headimgurl").length() > 0){
			member.set("headimgurl", apiResult.getStr("headimgurl")==null?"":
				apiResult.getStr("headimgurl").substring(0 , apiResult.getStr("headimgurl").length()-1));			
		}
		member.set("remark", apiResult.getStr("remark"));
		
		//清空缓存
		Set<String> keys = Redis.use().keys("*memlist*");
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next(); 
			Redis.use().del(key);
		}
		Member temp = Member.me.findById(member.getStr("id"));
		if (null == temp){
			member.save();
		}else{
			member.update();
		}
	}
	
	/**
	 * 编辑个人信息
	 * @param member
	 */
	@Before(Tx.class)
	public void edit(Member member){
		//清空缓存
		Set<String> keys = Redis.use().keys("*memlist*");
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next(); 
			Redis.use().del(key);
		}
		member.update();
	}
	
	/**
	 * 查找用户
	 * @param openid
	 * @return
	 */
	public Member findById(String openid){
		return Member.me.findById(openid);
	}
	
	/**
	 * 查找全部
	 * @param nickname
	 * @param stime
	 * @param etime
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findAll(String nickname , String stime , String etime , Integer pageNumber,Integer pageSize,
	           String orderField,String orderDirection,Map<String,Object> pagemap){
		StringBuffer sql = new StringBuffer("from member where 1=1 ");
		if (!stime.equals("")){
			sql.append(" and ctime >='"+stime+"'");
		}
		
		if (!etime.equals("")){
			sql.append(" and ctime <='"+etime+"'");
		}	
		if (!nickname.equals("")){
			sql.append(" and nickname like '%"+nickname+"%'");
		}
		sql.append(" order by "+orderField+" "+orderDirection);
		Page<Member> pm =null;
		if (Redis.use().get(nickname+stime+"memlist"+etime+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection) != null){
			pm = Redis.use().get(nickname+stime+"memlist"+etime+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection);
		}else{
			pm = Member.me.paginate(pageNumber, pageSize, "select * ", sql.toString());
			Redis.use().set(nickname+stime+"memlist"+etime+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection, pm);
		}
		for (Member member:pm.getList()){
			String quess = "select count(*) as questions from faqs where pid is null and mid=?";
			member.setQuestions(Db.queryLong(quess , member.getStr("id")));
			String reps = "select count(*) as reply from faqs where pid is not null and mid=?";
			member.setReply(Db.queryLong(reps , member.getStr("id")));
		}
		pagemap.put("pageSize", pm.getPageSize());//页面大小
		pagemap.put("totalRow", pm.getTotalRow());//总行数
		pagemap.put("pageCurrent", pm.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式 m
		pagemap.put("pageData", pm.getList());//页面数据
	}
	
	/**
	 * 获得所有被我关注的人
	 * @param mid
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findAllFollow(String mid , Integer pageNumber,Integer pageSize,
	           String orderField,String orderDirection,Map<String,Object> pagemap){
		StringBuffer sql = new StringBuffer("from member where id in(select bmid from followmember where mid='"+mid+"')");
		sql.append(" order by "+orderField+" "+orderDirection);
		Page<Member> pm =null;
		if (Redis.use().get(mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection) != null){
			pm = Redis.use().get(mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection);
		}else{
			pm = Member.me.paginate(pageNumber, pageSize, "select * ", sql.toString());
			Redis.use().set(mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection, pm);
		}
		pagemap.put("pageSize", pm.getPageSize());//页面大小
		pagemap.put("totalRow", pm.getTotalRow());//总行数
		pagemap.put("pageCurrent", pm.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式 m
		pagemap.put("pageData", pm.getList());//页面数据
	}
	
	/**
	 * 获得所有关注我的人
	 * @param mid
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findAllBfollow(String mid , Integer pageNumber,Integer pageSize,
	           String orderField,String orderDirection,Map<String,Object> pagemap){
		StringBuffer sql = new StringBuffer("from member where id in(select mid from followmember where bmid='"+mid+"')");
		sql.append(" order by "+orderField+" "+orderDirection);
		Page<Member> pm =null;
		if (Redis.use().get("b_"+mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection) != null){
			pm = Redis.use().get("b_"+mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection);
		}else{
			pm = Member.me.paginate(pageNumber, pageSize, "select * ", sql.toString());
			Redis.use().set("b_"+mid+"memlist"+"_"+pageNumber+"_"+pageSize+"_"+orderField+"_"+orderDirection, pm);
		}
		pagemap.put("pageSize", pm.getPageSize());//页面大小
		pagemap.put("totalRow", pm.getTotalRow());//总行数
		pagemap.put("pageCurrent", pm.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式 m
		pagemap.put("pageData", pm.getList());//页面数据
	}
	
	/**
	 * 得到个人提问的数量
	 * @return
	 */
	public int getAsks(String openid){
		String sql = "select count(*) from faqs where pid is null and mid=?";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;
	}
	
	/**
	 * 得到被个人回复的提问数
	 * @param openid
	 * @return
	 */
	public int getReplys(String openid){
		String sql = "select count(*) from faqs where id in(select distinct(pid) "
				+ "from faqs where mid=? and pid is not null)";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;
	}
	
	/**
	 * 得到被个人收藏回复数
	 * @param openid
	 * @return
	 */
	public int getCollections(String openid){
		String sql = "select count(*) from faqs where id in(select distinct(faqid)"
				+ " from faqcollection where mid=?)";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;
	}
	
	/**
	 * 得到被个人关注问题数
	 * @param openid
	 * @return
	 */
	public int getFollows(String openid){
		String sql = "select count(*) from follow where mid=?";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;
	}
	
	/**
	 * 得到被个人点赞回复数
	 * @param openid
	 * @return
	 */
	public int getPraise(String openid){
		String sql = "select count(*) from faqs where id in(select distinct(faqid)"
				+ " from faqpraise where mid=?)";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;
	}
	
	/**
	 * 查询用户是否被我关注过
	 * @param mid
	 * @param bmid
	 * @return
	 */
    public boolean isPraise(String mid , String bmid){
    	boolean praise = false;
    	List<Record> lr = Db.find("select * from followmember where mid=? and bmid=?" , mid , bmid);
    	if (null != lr && lr.size() > 0){
    		praise = true;
    	}
    	return praise;
    }
	
	/**
	 * 被我关注的人
	 * @param openid
	 * @return
	 */
	public int getPraisPersons(String openid){
		String sql = "select count(*) from followmember where mid=?";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;		
	}
	
	/**
	 * 关注我的人
	 * @param openid
	 * @return
	 */
	public int getPraisYous(String openid){
		String sql = "select count(*) from followmember where bmid=?";
		int count = Db.queryNumber(sql , openid).intValue();
		return count;		
	}
}
